package com.itheima.controller;

import com.itheima.mqtt.client.EmqClient;
import com.itheima.mqtt.enums.QosEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;


@RestController
@RequestMapping("/msg")
public class MsgController {

    private static final Logger log = LoggerFactory.getLogger(MsgController.class);


    @Autowired
    private EmqClient emqClient;

    @GetMapping("/publish/{topic}/{msg}")
    public ResponseEntity<String> publish(@PathVariable("topic") String topic, @PathVariable("msg") String msg) {
        log.info("emqx publish,topic={},msg={}", topic, msg);
        emqClient.publish(topic, msg, QosEnum.QoS2, false);
        return new ResponseEntity<>("success",HttpStatus.OK);
    }

    @GetMapping("/subscribe/{topic}/{qos}")
    public ResponseEntity<String> subscribe(@PathVariable("topic") String topic, @PathVariable("qos") Integer qos) {
        QosEnum qosEnum = QosEnum.valueOf(qos);
        if (qosEnum == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        if (emqClient.getSubscribedTopics().contains(topic)) {
            return new ResponseEntity<>("已经订阅过该主题", HttpStatus.CONFLICT);
        }
        log.info("emqx subscribe,topic={},Qos={}", topic, qos);
        emqClient.subscribe(topic, qosEnum);
        return new ResponseEntity<>("success",HttpStatus.OK);
    }

    @GetMapping("/unsubscribe/{topic}")
    public ResponseEntity<String> unsubscribe(@PathVariable("topic") String topic) {
        log.info("emqx unsubscribe,topic={}", topic);
        emqClient.unSubscribe(topic);
        return new ResponseEntity<>("success",HttpStatus.OK);
    }

    @GetMapping("/topics")
    public ResponseEntity<Set<String>> getSubscribedTopics() {
        return new ResponseEntity<>(emqClient.getSubscribedTopics(), HttpStatus.OK);
    }
}
